<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="path" label="path">
                <el-input
                    :disabled="isDetail"
                    v-model="form.path"
                    placeholder="请填写接口路径 如：/api/bill/:id/"
                ></el-input>
            </el-form-item>
            <el-form-item prop="methods" label="methods">
                <el-checkbox-group :disabled="isDetail" v-model="form.methods">
                    <el-checkbox v-for="item in METHODS_TYPE" :key="item" :label="item" name="type">{{
                        item
                    }}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="isDetail"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isDetail"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import {postApiList, putApiList} from '@/api/permission';
import {METHODS_TYPE} from '@/views/system/interface/constants';

const validatePath = (rule, value, callback) => {
    if (typeof value !== 'string' || /^\/[A-z|:|,|/]+\/{0,1}$/.test(value)) {
        callback();
        return;
    }
    callback(new Error('path格式不正确'));
};
export const RULES = {
    path: [
        {required: true, message: 'path必填项', trigger: ['change', 'blur']},
        {validator: validatePath, trigger: ['change', 'blur']}
    ],
    methods: [{required: true, message: 'methods必填项', trigger: ['change', 'blur']}]
    // remark: [{required: false, message: '请填角色备注', trigger: ['change', 'blur']}]
};

export default {
    name: 'center-dialog',
    props: {
        title: {
            type: String,
            default: ''
        },
        visible: {
            type: Boolean,
            default: false
        },
        dataSource: {
            type: Object,
            required: true
        }
    },
    components: {},
    data() {
        return {
            METHODS_TYPE,
            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            // 新建表单
            form: {
                id: undefined,
                path: '',
                methods: [],
                remark: ''
            },
            rules: RULES
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.form = {
                    ...this.form,
                    ...val,
                    path: val.path,
                    methods: val.methods,
                    remark: val.remark
                };
            },
            immediate: true
        }
    },
    methods: {
        // 提交表单
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                if (valid) {
                    const {_id, path, remark, methods} = this.form;
                    const newItem = {
                        _id,
                        path,
                        remark,
                        methods
                    };

                    if (this.title && this.title.includes('添加')) {
                        this.onCreate(newItem);
                    }
                    if (this.title && this.title.includes('编辑')) {
                        this.onPutData(newItem);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建角色
        onCreate(newItem) {
            this.centerDialogLoading = true;
            postApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    const data = error.response && error.response.data;

                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '创建失败'});
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        onPutData(newItem) {
            this.centerDialogLoading = true;
            putApiList(newItem._id, newItem)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.form = {
                id: undefined,
                path: '',
                remark: '',
                methods: []
            };
        }
    }
};
</script>
